package com.yan.test.work.testpaging3.net.response;

import android.text.TextUtils;


import com.yan.test.work.testpaging3.net.JsonContervUtil;
import com.yan.test.work.testpaging3.net.L;
import com.yan.test.work.testpaging3.net.ThreadUtil;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.Response;

/**
 * Created by ywy on 2018-12-21.
 */
public abstract class CallBackBean implements Callback {


    int stateCode;

    public int getStateCode() {
        return stateCode;
    }

    /**
     * 请求成功时回调
     *
     * @param responseBean 响应数据
     */
    public abstract void onSuccess(BaseResponseBean responseBean);

    public void onSuccessGoMain(final BaseResponseBean responseBean) {
        ThreadUtil.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                onSuccess(responseBean);
            }
        });
    }

    /**
     * 网络访问结束回调
     */
    public void onFinish() {

    }

    public void onFinishGoMain() {
        ThreadUtil.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                onFinish();
            }
        });
    }

    /**
     * 请求失败时回调
     */
    public abstract void onFailure(BaseResponseBean responseBean, Exception e);

    public void onFailureGoMain(final BaseResponseBean responseBean, final Exception e) {
        ThreadUtil.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                onFailure(responseBean, e);
            }
        });
    }

    @Override
    public void onFailure(Call call, final IOException e) {

        String requsetUrl = call.request().url().toString();
        int index = requsetUrl.indexOf("?");
        if(index == -1) index = requsetUrl.length();
        String newUrl = requsetUrl.substring(0, index);

        if(call.isCanceled()){
            onFinishGoMain();
        }else{
            BaseResponseBean baseResponseBean = new BaseResponseBean();
            baseResponseBean.resp_code = -1;
            baseResponseBean.resp_msg = "La solicitud falló";
            loge(baseResponseBean.resp_msg, e);
            onFailureGoMain(baseResponseBean, e);
            onFinishGoMain();
        }


    }

    @Override
    public void onResponse(final Call call, final Response response) throws IOException {

        String requsetUrl = call.request().url().toString();
        int index = requsetUrl.indexOf("?");
        if(index == -1) index = requsetUrl.length();
        String newUrl = requsetUrl.substring(0, index);
        try {
            if (response.isSuccessful()) {
                onSuccess(call, response);
            } else {
                onFailure(call, response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
//        onFinishGoMain();

    }

    public void onFailure(Call call, Response response) throws IOException {
        // http请求失败，默认处理
        int statusCode = response.code();
        stateCode = statusCode;
        printResponse(statusCode, call, response.headers(), response.body().string(), new Exception(response.body().toString()));
        BaseResponseBean resultBean = new BaseResponseBean();
        resultBean.resp_code = -1;
        resultBean.resp_msg = "La solicitud falló";
        onFailureGoMain(resultBean, new Exception(resultBean.resp_msg));
        onFinishGoMain();
    }

    private void printResponse(int statusCode, Call call, Headers headers, String responseString, Throwable throwable) {
        if (throwable == null) {
            log("------http请求成功------");
        } else {
            log("------http请求失败------");
            log("异常描述：" + throwable.getMessage());
        }
        String requestURI = call.request().url().toString();
        if (requestURI != null) {
            log("请求地址：" + requestURI.toString());
        }
        log("响应状态码：" + statusCode);
        StringBuffer headerSb = new StringBuffer();
        if (headers != null) {
            for (String key : headers.names()) {
                String headerStr = headers.get(key);
                headerSb.append(key).append("=").append(headerStr).append(";");

            }
        }
        log("响应头：" + headerSb);
        log("响应数据：" + responseString);
    }


    public void onSuccess(Call call, Response response) throws IOException {
        Headers headers = response.headers();
        String responseString = response.body().string();
        int statusCode = response.code();
        stateCode = statusCode;
        printResponse(statusCode, call, headers, responseString, null);
        if (TextUtils.isEmpty(responseString)) {
            BaseResponseBean baseResponseBean = new BaseResponseBean();
            baseResponseBean.resp_code = -1;
            baseResponseBean.resp_msg = "La solicitud falló";
            onFailureGoMain(baseResponseBean, new Exception(baseResponseBean.resp_msg));
            onFinishGoMain();
            return;
        }


        BaseResponseBean responseBean;
        try {
            responseBean = JsonContervUtil.jsonToObject(responseString , BaseResponseBean.class);
            if(responseBean.resp_code == 1000){
                onSuccessGoMain(responseBean);
                onFinishGoMain();
            }else{

                //token到期
                if(responseBean.resp_code == -1000){

                }

                onFailureGoMain(responseBean , new Exception("responseBean.resp_msg"));
                onFinishGoMain();
            }

        } catch (Exception e) {
            e.printStackTrace();
            responseBean = new BaseResponseBean();
            responseBean.resp_code = -1;
            responseBean.resp_msg = "La solicitud falló";
            onFailureGoMain(responseBean , new Exception(responseBean.resp_msg));
            onFinishGoMain();
        }
    }

    private void log(String msg) {
        L.d(CallBackBean.class, msg);
    }

    private void loge(String msg, Exception e) {
        L.e(CallBackBean.class, msg, e);
    }


//    private void show(final String msg) {
//        ThreadUtil.runOnMainThread(new Runnable() {
//            @Override
//            public void run() {
//                com.bbrightway.library.util.T.showMsgS(IWMSApp.getAppContext(), msg);
//            }
//        });
//    }
//
//    private void logout() {
//        show(ResponseStatus.PERMISSION_DENIED.getMsg());
//        CookieUtils.clear();
//        ActivityManager.getInstance().finishAllActivity();
//        Intent intent = new Intent();
//        intent.setAction("com.bbrightway.iwms.pcitc.app.login");
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        try {
//            IWMSApp.getAppContext().startActivity(intent);
//        } catch (Exception e) {
//            e.printStackTrace();
//            L.e("CallBackBean", "exit");
//        }
//
//
//    }

}
